<template>
    <div style="margin-left: 10px">
        <div>
            <div>
                <el-input
                    style="width: 60%"
                    placeholder="请输入接口名称"
                    v-model.trim="name"
                    clearable>
                    <template slot="prepend">接口名称 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</template>
                </el-input>
                <el-button
                    slot="append"
                    type="primary"
                    @click="save = !save">Save
                </el-button>
                <el-button
                    style="margin-left: 0px"
                    type="success"
                    @click="reverseStatus"
                    v-loading="loading"
                    :disabled="loading">Send
                </el-button>
            </div>
            <div>
                <el-input
                    style="width: 60%; margin-top: 10px"
                    placeholder="请输入接口请求地址"
                    v-model.trim="url"
                    clearable>
                    <el-select
                        style="width: 125px"
                        slot="prepend"
                        v-model="method">
                        <el-option
                            v-for="item of httpOptions"
                            :label="item.label"
                            :value="item.label"
                            :key="item.value">
                        </el-option>
                    </el-select>

                </el-input>

                <el-tooltip
                    effect="dark"
                    content="循环次数"
                    placement="bottom">
                    <el-input-number
                        v-model="times"
                        controls-position="right"
                        :min="1"
                        :max="20"
                        style="width: 12%"
                        :precision="0">
                    </el-input-number>
                </el-tooltip>

            </div>
        </div>

        <div class="request">
            <el-dialog
                v-if="dialogTableVisible"
                :visible.sync="dialogTableVisible"
                width="70%">
                <report :summary="summary"></report>
            </el-dialog>

            <el-tabs
                style="margin-left: 20px;"
                v-model="activeTag"
                @tab-click="clickTab"
                :before-leave='leaveTab'>
                <el-tab-pane label="Header" name="first">
                    <headers
                        :save="save"
                        v-on:header="handleHeader"
                        :header="response ? response.body.header: [] ">
                    </headers>
                </el-tab-pane>

                <el-tab-pane label="Request" name="second">
                    <request
                        :save="save"
                        v-on:request="handleRequest"
                        ref="request"
                        :request="response ? response.body.request: []">
                    </request>
                </el-tab-pane>

                <el-tab-pane label="Variables" name="five">
                    <variables
                        :save="save"
                        v-on:variables="handleVariables"
                        ref="variables"
                        :variables="response ? response.body.variables : []"
                        :hideoptions="hideoptions"
                    >

                    </variables>
                </el-tab-pane>

                <el-tab-pane label="Extract" name="third">
                    <Extract
                        :save="save"
                        v-on:extract="handleExtract"
                        :extract="response ? response.body.extract : []"
                        :api_resp="summary.details?summary.details[0].records[0].meta_data.response:{}">
                    </Extract>
                </el-tab-pane>

                <el-tab-pane label="Validate" name="fourth">
                    <validate
                        :save="save"
                        v-on:validate="handleValidate"
                        :validate="response ? response.body.validate: []"
                        :api_resp="summary.details?summary.details[0].records[0].meta_data.response:{}">
                    </validate>
                </el-tab-pane>


                <el-tab-pane label="Hooks" name="six">
                    <hooks
                        :save="save"
                        v-on:hooks="handleHooks"
                        :hooks="response ? response.body.hooks: []">
                    </hooks>
                </el-tab-pane>
            </el-tabs>

        </div>
    </div>

</template>

<script>
import Headers from '../../../httprunner/components/Headers'
import Request from '../../../httprunner/components/Request'
import Extract from '../../../httprunner/components/Extract'
import Validate from '../../../httprunner/components/Validate'
import Variables from '../../../httprunner/components/Variables'
import Hooks from '../../../httprunner/components/Hooks'
import Report from '../../../reports/DebugReport'

export default {
    components: {
        Headers,
        Request,
        Extract,
        Validate,
        Variables,
        Hooks,
        Report
    },

    props: {
        host: {
            require: false
        },
        nodeId: {
            require: false
        },
        project: {
            require: false
        },
        config: {
            require: false
        },
        response: {
            require: true
        }
    },
    methods: {
        // 点击tab时触发
        clickTab(tab) {
            console.log('变更', tab.label);
            if (tab.label === 'Variables') {
                // 从formData中提取变量
                let formData = this.$refs['request'].formData;
                formData.forEach(item => {
                    if (item.key != "" || item.key != null) {
                        let add_flag = true;
                        // 判断变量是否已存在
                        this.response.body.variables.forEach(vitem => {
                            if (item.key === vitem.key) {
                                add_flag = false
                            }
                        });
                        // 新增变量
                        if (add_flag) {
                            this.response.body.variables.push({
                                'key': item.key,
                                'value': '',
                                'desc': item.desc,
                                'type': 1,
                            })
                        }
                    }
                });

                // 从paramsData中提取变量
                let paramsData = this.$refs['request'].paramsData;
                paramsData.forEach(item => {
                    let add_flag = true;
                    // 判断变量是否已存在
                    this.response.body.variables.forEach(vitem => {
                        if (item.key === vitem.key) {
                            add_flag = false
                        }
                    });
                    // 新增变量
                    if (add_flag) {
                        this.response.body.variables.push({
                            'key': item.key,
                            'value': '',
                            'desc': item.desc,
                            'type': 1,
                        })
                    }
                });

                // 从jsonData中提取变量
                let jsonData = this.$refs['request'].jsonData
                if (jsonData != "" || jsonData != null) {
                    let patt = new RegExp('(?<=[\$])[^{].*?[^}](?=["])', "g");
                    let result = jsonData.match(patt)
                    //正则提取变量，没变量就return
                    if (result == null) {
                        return
                    }
                    if (this.response.body.variables[0]['key'] != "") {
                        this.response.body.variables.forEach(item => {
                            let index = result.indexOf(item["key"]);
                            if (index != -1) {
                                result.splice(index, 1);
                            }
                        });
                    }
                    if (result.length > 0) {
                        if (this.response.body.variables[0]['key'] == "") {
                            this.response.body.variables = []
                        }
                        result.forEach(item => {
                            this.response.body.variables.push({
                                'key': item,
                                'value': '',
                                'desc': "",
                                'type': 1,
                            })
                        });

                    }
                }
            }

        },
        // 离开tab时触发
        leaveTab(activeName, oldActiveName) {
            // console.log("activeName:",activeName);
            // console.log("oldActiveName:",oldActiveName);
            if (oldActiveName === 'five') {
                // 离开Variables时，将Variables保存
                // console.log("this.$refs['variables'].tableData:", this.$refs['variables'].tableData);
                this.response.body.variables = this.$refs['variables'].tableData;
            }
        },

        reverseStatus() {
            this.save = !this.save;
            this.run = true;
        },

        handleHeader(header) {
            this.header = header;
        },
        handleRequest(request) {
            this.request = request;
        },
        handleValidate(validate) {
            this.validate = validate;
        },
        handleExtract(extract) {
            this.extract = extract;
        },
        handleVariables(variables) {
            this.variables = variables;
        },
        handleHooks(hooks) {
            this.hooks = hooks;

            if (!this.run) {
                if (this.id === '') {
                    this.addAPI();
                } else {
                    this.updateAPI();
                }
            } else {
                this.runAPI();
                this.run = false;
            }
        },

        validateData() {
            if (this.url === '') {
                this.$notify.error('接口请求地址不能为空');
                return false;
            }

            if (this.name === '') {
                this.$notify.error('接口名称不能为空');
                return false;
            }
            return true
        },
        updateAPI() {
            if (this.validateData()) {
                this.$api.updateAPI(this.id, {
                    header: this.header,
                    request: this.request,
                    extract: this.extract,
                    validate: this.validate,
                    variables: this.variables,
                    hooks: this.hooks,
                    url: this.url,
                    method: this.method,
                    name: this.name,
                    times: this.times,
                }).then(resp => {
                    if (resp.success) {
                        this.$notify.success(resp.msg);
                        this.$emit("addSuccess");
                    } else {
                        this.$notify.error(resp.msg)
                    }
                })
            }
        },

        runAPI() {
            console.log("run api....")
            if (this.validateData()) {
                this.loading = true;
                this.$api.runSingleAPI({
                    header: this.header,
                    request: this.request,
                    extract: this.extract,
                    validate: this.validate,
                    variables: this.variables,
                    hooks: this.hooks,
                    url: this.url,
                    method: this.method,
                    name: this.name,
                    times: this.times,
                    project: this.project,
                    config: this.config,
                    host: this.host
                }).then(resp => {
                    console.log("api resp:", resp);
                    this.summary = resp;
                    this.dialogTableVisible = true;
                    this.loading = false;
                }).catch(resp => {
                    //this.$notify.error("接口响应异常");
                    this.loading = false;
                })
            }
        },

        addAPI() {
            if (this.validateData()) {
                this.$api.addAPI({
                    header: this.header,
                    request: this.request,
                    extract: this.extract,
                    validate: this.validate,
                    variables: this.variables,
                    hooks: this.hooks,
                    url: this.url,
                    method: this.method,
                    name: this.name,
                    times: this.times,
                    nodeId: this.nodeId,
                    project: this.project
                }).then(resp => {
                    if (resp.success) {
                        this.$notify.success(resp.msg);
                        this.$emit("addSuccess");
                    } else {
                        this.$notify.error(resp.msg)
                    }
                })
            }
        }
    },

    watch: {
        response: function () {
            this.name = this.response.body.name;
            this.method = this.response.body.method;
            this.url = this.response.body.url;
            this.times = this.response.body.times;
            this.id = this.response.id;
        }
    },
    data() {
        return {
            loading: false,
            times: 1,
            name: '',
            url: '',
            id: '',
            header: [],
            request: {},
            extract: [],
            validate: [],
            variables: [],
            hooks: [],
            method: 'GET',
            dialogTableVisible: false,
            save: false,
            hideoptions: true,
            run: false,
            summary: {},
            activeTag: 'second',
            httpOptions: [{
                label: 'GET',
            }, {
                label: 'POST',
            }, {
                label: 'PUT',
            }, {
                label: 'DELETE',
            }, {
                label: 'HEAD',
            }, {
                label: 'OPTIONS',
            }, {
                label: 'PATCH',
            }],
        }
    },
    name: "ApiBody"
}
</script>

<style scoped>
.request {
    margin-top: 15px;
    border: 1px solid #ddd;
}


</style>
